package controllers;

import java.util.Date;

import javax.annotation.Resource;

import com.google.gson.Gson;
import com.google.gson.JsonParser;
import models.ru.paralainer.chat.server.annotations.HttpBasic;
import models.ru.paralainer.chat.server.dao.MessageDAO;
import models.ru.paralainer.chat.server.domain.Message;
import models.ru.paralainer.chat.server.dto.ErrorDTO;
import models.ru.paralainer.chat.server.dto.MessageCreateRequestDTO;
import models.ru.paralainer.chat.server.dto.MessageCreateResponseDTO;
import models.ru.paralainer.chat.server.dto.MessageListResponseDTO;
import org.apache.commons.lang.StringUtils;


/**
 * User: stalov
 * Date: 22.05.12
 * Time: 10:00
 */

public class MessageController extends BaseController {

    @HttpBasic
    public static void getAll() {
        renderJSON(new MessageListResponseDTO(MessageDAO.INSTANCE.getAll()));
    }

    @HttpBasic
    public static void getOlder(Long messageId) {
        if (messageId == null){
            renderJSON(new ErrorDTO("Message ID is null"));
        }
        renderJSON(new MessageListResponseDTO(MessageDAO.INSTANCE.getOlderByMessageId(messageId)));
    }

    @HttpBasic
    public static void addMessage() {
        MessageCreateRequestDTO request = parseRequest(MessageCreateRequestDTO.class);
        if (request == null || StringUtils.isBlank(request.getText())) {
            renderJSON(new ErrorDTO("Message text is empty"));
            return;
        }
        Message message = new Message();
        message.setDate(new Date());
        message.setText(request.getText());
        message.setUser(fetchUser());
        message.save();
        renderJSON(new MessageCreateResponseDTO(message.getId()));
    }

}
